package com.common.www.controller.file;

import com.common.www.MyApplicationListener;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.file.FileCommon;
import com.common.www.data.NetCode;
import com.common.www.service.file.FileService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.TxtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@CrossOrigin()
@RequestMapping(value = {"/api/file/"})
@Api(tags = "api 文件上传相关接口")
public class FileController {

    @Value("${wmp.upload.rootPath}")
    private String fileRootPath;

    @Autowired
    private FileService fileService;

    @ApiOperation(value = "批量上传文件接口", nickname = "", notes = "")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "module", value = "对应模块名景观工程 传 scenery", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/uploadFiles", produces = {"application/json"}, method = RequestMethod.POST)
    public Result uploadFiles(MultipartFile[] uploadFiles, String module) {
        if (TxtUtil.isEmpty(module)) {
            return R.fail("请上传模块名");
        }
        List<FileCommon> list = new ArrayList<>();
        try {
            if (uploadFiles != null && uploadFiles.length > 0) {
                for (MultipartFile imageFile : uploadFiles) {
                    if (imageFile != null && imageFile.getSize() > 0) {
                        FileCommon tempFileCommon = fileService.saveFile(imageFile, module, true, true);
//                        System.out.println("文件访问地址  " + fileRootPath);
                        list.add(tempFileCommon);
                    } else {

                    }
                }
            }
        } catch (Exception e) {
            return R.fail(String.format("上传出现异常！"));
        }
        if (list.size() == 0)
            return R.fail(String.format("上传文件错误！"));

        return R.ok("上传保存成功", list);

    }


    @ApiOperation(value = "通用上传文件接口", nickname = "", notes = "")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "module", value = "对应模块名", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/uploadSingleFile", produces = {"application/json"}, method = RequestMethod.POST)
    public Result uploadSingleFile(MultipartFile uploadFile, String module) {
        if (TxtUtil.isEmpty(module)) {
            return R.fail("请上传模块名");
        }
        FileCommon fileCommon = null;
        try {
            if (uploadFile != null && uploadFile.getSize() > 0) {
                fileCommon = fileService.saveFile(uploadFile, module, true, true);
//                        System.out.println("文件访问地址  " + fileRootPath);
            } else {

            }
        } catch (Exception e) {
            return R.fail(String.format("上传出现异常！"));
        }
        if (fileCommon == null)
            return R.fail(String.format("上传文件错误！"));

        return R.ok("上传保存成功", fileCommon);

    }

    @ApiOperation(value = "文件动态下载", nickname = "", notes = "")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/downloadFile", produces = {"application/json"}, method = {RequestMethod.POST, RequestMethod.GET})
    public Result downloadFile(HttpServletResponse response, Long id) {
        FileCommon fileCommon = fileService.findOne(id);
        if (fileCommon == null) {
            return R.fail("文件不存在");
        }

        File file = new File(MyApplicationListener.fileRootPath + File.separator + fileCommon.getAbsPath());


        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(file.getAbsolutePath()));
            String[] dir = file.getAbsolutePath().split("/");
            String fileName = fileCommon.getSrcName();
            String[] array = fileName.split("[.]");
            String fileType = array[array.length - 1].toLowerCase();
            //设置文件ContentType类型
            response.setContentType("application/binary;charset=UTF-8");
            //设置文件头：最后一个参数是设置下载文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {
//            logger.error("responseFileStream error:FileNotFoundException" + e.toString());
        } catch (Exception e) {
//            logger.error("responseFileStream error:" + e.toString());
        } finally {
            try {
                out.close();
                in.close();
            } catch (NullPointerException e) {
//                logger.error("responseFileStream stream close() error:NullPointerException" + e.toString());
            } catch (Exception e) {
//                logger.error("responseFileStream stream close() error:" + e.toString());
            }
        }

        return R.ok();
    }

    @ApiOperation(value = "获取测试", nickname = "", notes = "")
    @RequestMapping(value = "/ipTest", produces = {"application/json"}, method = RequestMethod.POST)
    public Result ipTest() {
        return R.ok(fileService.getProjectPath());
    }


    @ApiOperation("删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public Result deleteFile(Long fileId) {
        if (ParamsUtils.isInputEmpty(fileId)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        FileCommon fileCommon = fileService.findOne(fileId);
        if (fileCommon == null) {
            return R.fail("文件已删除");
        }

        String path = fileService.getFileRootPath() + File.separator + fileCommon.getAbsPath();
        File file = new File(path);
        file.delete();

        fileService.delete(fileId);

        return R.ok("删除成功");
    }


    @ApiOperation(value = "通用上传文件接口", nickname = "", notes = "")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "module", value = "对应模块名", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/uploadSingleFileFromBase64", produces = {"application/json"}, method = RequestMethod.POST)
    public Result uploadSingleFileFromBase64(String base64, String module) {
        if (TxtUtil.isEmpty(module)) {
            return R.fail("请上传模块名");
        }
        FileCommon fileCommon = null;
        try {
            fileCommon = fileService.saveFile(base64, module);
//                        System.out.println("文件访问地址  " + fileRootPath);
        } catch (Exception e) {
            return R.fail(String.format("上传出现异常！"));
        }
        if (fileCommon == null)
            return R.fail(String.format("上传文件错误！"));

        return R.ok("上传保存成功", fileCommon);

    }


}
